package com.cloud.wms.ui.in.fragment;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.utils.TimeUtils;
import com.cloud.widget.ScanText;
import com.cloud.widget.expand.ExpandLayout;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.ui.in.contract.InInventoryContract;
import com.cloud.wms.ui.in.entity.InCommodityEntity;
import com.cloud.wms.ui.in.entity.InOrderEntity;
import com.cloud.wms.ui.in.inventory.SwitchBatchActivity;
import com.cloud.wms.ui.in.presnter.InInventoryPresenter;
import com.cloud.wms.ui.main.entity.BatchEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.widget.dialog.TaskCompleteDialog;
import com.trello.rxlifecycle3.LifecycleTransformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-24 16:59
 * @Description: 菜单--逐件清点
 */
public class HaveSingleFragment extends BaseViewPagerFragment<InInventoryPresenter> implements InInventoryContract.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.btn_good)
    CheckedTextView btnGood;
    @BindView(R.id.btn_bad)
    CheckedTextView btnBad;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.iv_switch_batch)
    CheckedTextView ivSwitchBatch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    private InOrderEntity inOrder;
    private InCommodityEntity commodityEntity;
    private BaseQuickAdapter<InCommodityEntity, BaseViewHolder> mAdapter;
    private TaskEntity taskEntity;
    private String beginTime;

    @Override
    protected int getResId() {
        return R.layout.fragment_in_inventory_have_single;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        beginTime = TimeUtils.getCurrentDateAndTime();
        inOrder = getArguments().getParcelable("InOrder");
        taskEntity = getArguments().getParcelable("Task");

        if (inOrder != null)
            tvMemberName.setText(inOrder.getMemberName());
        else
            tvMemberName.setText(taskEntity.getMemberName());
        btnSubmit.setEnabled(false);
        btnGood.setChecked(true);

        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new BaseQuickAdapter<InCommodityEntity, BaseViewHolder>(R.layout.item_common_commodity) {
            @Override
            protected void convert(BaseViewHolder helper, InCommodityEntity item) {
                helper.setText(R.id.tv_commodity_name, item.getCommodityName())
                        .setText(R.id.tv_commodity_code, item.getBarCode())
                        .setText(R.id.tv_commodity_type, item.getStockType() == 1 ? "良品" : "次品")
                        .setText(R.id.tv_commodity_amount, item.getAmount() + "")
                        .setText(R.id.tv_produce_date, item.getProductionDate())
                        .setText(R.id.tv_deadline_date, item.getExpirationDate())
                        .setText(R.id.tv_in_date, item.getInDate());

                ImageView ivArrow = helper.getView(R.id.iv_arrow);
                ExpandLayout expand = helper.getView(R.id.expand_layout);
                expand.setOnExpansionUpdateListener((expansionFraction, state) -> ivArrow.setRotation(expansionFraction * 180));
                helper.getView(R.id.ll_title_content).setOnClickListener(v -> expand.toggle(true));
            }
        };
        rvList.setItemAnimator(new DefaultItemAnimator());
        rvList.setAdapter(mAdapter);

        mAdapter.setNewInstance(new ArrayList<InCommodityEntity>());
    }

    @Override
    public ScanText getScanText() {
        return scanText;
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        if (!ivSwitchBatch.isChecked()) {
            InCommodityEntity entity = null;
            for (int i = 0; i < mAdapter.getData().size(); i++) {
                InCommodityEntity inCommodityEntity = mAdapter.getData().get(i);
                int commodityType = 1;
                if (btnBad.isChecked()) commodityType = 2;
                if (inCommodityEntity.matchBarCode(result) && inCommodityEntity.getStockType() == commodityType) {
                    entity = inCommodityEntity;
                    entity.setAmount(entity.getAmount() + 1);
                    mAdapter.notifyDataSetChanged();
                    return;
                }
            }
        }
        mPresenter.checkCommodityCode(inOrder != null ? String.valueOf(inOrder.getInID()) :  taskEntity.getMainBillID() + "", result);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case InInventoryPresenter.IN_CHECK_CODE:
                commodityEntity = (InCommodityEntity) message.obj;
//                tvMemberName.setText(commodityEntity.getMemberName());
                SwitchBatchActivity.start(getActivity());
                break;
            case InInventoryPresenter.IN_SINGLE_SUBMIT:
                success("清点提交成功!");
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                mPresenter.loadInCommodityList(inOrder != null ? String.valueOf(inOrder.getInID()) :  taskEntity.getMainBillID() + "", false);
                break;
            case InInventoryPresenter.CHECK_COMPLETE:
                new TaskCompleteDialog(getActivity()).show();
                break;
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventCome(Event event) {
        if (event == null) {
            return;
        }
        switch (event.getCode()) {
            case EventConfig.SWITCH_BATCH:
                if (commodityEntity.isBatch()) {
                    ivSwitchBatch.setChecked(false);
                    BatchEntity batchEntity = (BatchEntity) event.getData();
                    commodityEntity.setProductionDate(batchEntity.getProductionDate());
                    commodityEntity.setInDate(batchEntity.getInDate());
                    commodityEntity.setExpirationDate(batchEntity.getExpirationDate());
                    commodityEntity.setAmount(commodityEntity.getAmount() + 1);
                    commodityEntity.setStockType(btnGood.isChecked() ? 1 : 2);
                    mAdapter.addData(0, commodityEntity);
                    commodityEntity = null;
                }
                btnSubmit.setEnabled(true);
                break;
        }
    }

    @OnClick({R.id.iv_switch_batch, R.id.btn_good, R.id.btn_bad, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_switch_batch:
                ivSwitchBatch.setChecked(!ivSwitchBatch.isChecked());
                break;
            case R.id.btn_good:
                btnGood.setChecked(true);
                btnBad.setChecked(false);
                switchCommodityType();
                break;
            case R.id.btn_bad:
                btnGood.setChecked(false);
                btnBad.setChecked(true);
                switchCommodityType();
                break;
            case R.id.btn_submit:
                mPresenter.submitSingleInventory(taskEntity, inOrder, mAdapter.getData(), beginTime);
                break;
        }
    }

    private void switchCommodityType() {
        if (commodityEntity != null) {
            int commodityType = 1;
            if (btnBad.isChecked()) commodityType = 2;
            commodityEntity.setStockType(commodityType);
        }
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    public static BaseViewPagerFragment newInstance(Bundle bundle) {
        HaveSingleFragment fragment = new HaveSingleFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
}
